#!/bin/bash

set -e

ACTION=$1

if [ "$EUID" -ne 0 ]; then
    echo "This script must be run as root or with sudo."
    exit 1
fi

VENDOR_NAME=$(cat "/sys/class/dmi/id/sys_vendor")
PRODUCT_NAME=$(cat "/sys/class/dmi/id/product_name")
BOARD_NAME=$(cat "/sys/class/dmi/id/board_name")

if [[ -f "/usr/libexec/screen-rotate" ]]; then
    source "/usr/libexec/screen-rotate" || true
fi

boot_mountpoint=""
if mountpoint -q /efi; then
    boot_mountpoint="/efi"
elif mountpoint -q /boot; then
    boot_mountpoint="/boot"
elif mountpoint -q /frzr_root/boot; then
    boot_mountpoint="/frzr_root/boot"
else
    echo "No boot partition found."
    exit 1
fi

if [[ "$boot_mountpoint" == "/frzr_root/boot" ]]; then
    device=$(findmnt -n -o SOURCE --target /frzr_root/boot)
    mount $device /boot
    boot_mountpoint="/boot"
fi

function install_refind() {
    if [ -x "$(command -v refind-install)" ]; then
        refind-install
    else
        echo "rEFInd is not installed."
        exit 1
    fi
    if [ -f "$boot_mountpoint/refind_linux.conf" ]; then
        rm -f "$boot_mountpoint/refind_linux.conf"
    fi
    if [ -f "/boot/refind_linux.conf" ]; then
        rm -f "/boot/refind_linux.conf"
    fi
    if [ ! -f "$boot_mountpoint/EFI/refind/refind.conf-sample" ]; then
        cp /usr/share/refind/refind.conf-sample "$boot_mountpoint/EFI/refind/refind.conf-sample"
    fi
}

function uninstall_refind() {
    boot=$(efibootmgr | grep "rEFInd Boot Manager" | grep -i "REFIND_X64.EFI" | awk '{print $1}' | sed 's/Boot//' | sed 's/\*//')
    if [ -n "$boot" ]; then
        efibootmgr -b $boot -B
    fi
    if [ -d "$boot_mountpoint/EFI/refind" ]; then
        rm -rf "$boot_mountpoint/EFI/refind"
    fi
    echo "rEFInd uninstalled."
}

function set_all_config() {
    local refind_dir=$1
    local theme_conf=$2
    local theme_option=''
    if [ -n "$theme_conf" ]; then
        theme_option="include $theme_conf"
    fi

    if [ -f "$refind_dir/refind.conf" ]; then
        mv "$refind_dir/refind.conf" "$refind_dir/refind.conf.bak"
    fi

    local _enable_mouse=""
    if [[ "$VENDOR_NAME" == "Micro-Star International Co., Ltd." && "$BOARD_NAME" == "MS-1T"* ]]; then
        _enable_mouse="enable_mouse"
    fi

    local _screen_rotation=""
    if [ -n "$ROTATE_OFFSET" ]; then
        _screen_rotation="screen_rotation $((ROTATE_OFFSET * 90))"
    fi

    touch "$refind_dir/override.conf"

    cat >"$refind_dir/refind.conf" <<-EOF
timeout 3
use_nvram false
dont_scan_dirs frzr_efi:EFI/boot,EFI/systemd,EFI/UMAF,EFI/Shell/
dont_scan_files DisplayEngine.efi,SetupBrowser.efi,UiApp.efi,umaf.efi,modelist.efi
scan_all_linux_kernels false
write_systemd_vars true

$_enable_mouse
$_screen_rotation

include skorionos.conf
$theme_option

# override 
include override.conf
EOF
}

function set_boot_config() {
    local refind_dir=$1
    local icon=${2:-"EFI/refind/icons/os_arch.png"}

    if [ -f "$refind_dir/skorionos.conf" ]; then
        mv "$refind_dir/skorionos.conf" "$refind_dir/skorionos.conf.bak"
    fi

    cat >"$refind_dir/skorionos.conf" <<-EOF
menuentry "SkorionOS" {
    icon     $icon
    loader   EFI/systemd/systemd-bootx64.efi
}
EOF
}

function setup_refind_tool() {
    refind_tool_dir="$boot_mountpoint/EFI/tools"
    if [ ! -d "$refind_tool_dir" ]; then
        mkdir -p "$refind_tool_dir"
    fi

    for efi in "$boot_mountpoint/EFI/Shell"/*.efi; do
        if [ -f "$efi" ]; then
            cp "$efi" "$refind_tool_dir"
        fi
    done
}

function setup_refind() {
    copy_refind_theme_regular
    convert_skorionos_icon
    setup_refind_tool
    copy_efi_drivers
    
    refind_dir="$boot_mountpoint/EFI/refind"
    if [ ! -d "$refind_dir" ]; then
        echo "rEFInd boot directory not found."
        exit 1
    fi

    refind_icon_dir="$boot_mountpoint/EFI/refind/themes/refind-theme-regular/icons"


    # Set the theme
    theme_conf_option=""
    icon_option=""
    if [ -f "$dst_theme_path/theme_dark.conf" ]; then
        theme_conf_option="themes/refind-theme-regular/theme_dark.conf"
        # icon_option="EFI/refind/themes/refind-theme-regular/icons/128-48/os_steam.png"
    fi
    if [ -f "$refind_icon_dir/128-48/os_skorion.png" ]; then
        icon_option="EFI/refind/themes/refind-theme-regular/icons/128-48/os_skorion.png"
    else
        icon_option="EFI/refind/themes/refind-theme-regular/icons/128-48/os_steam.png"
    fi

    set_all_config $refind_dir $theme_conf_option
    set_boot_config $refind_dir $icon_option

    efibootmgr -N 2>/dev/null || true

    echo "rEFInd setup complete."
}

function copy_refind_theme_regular() {
    src_theme_path="/usr/local/share/sk-pre/refind/refind-theme-regular"
    dst_theme_path="$boot_mountpoint/EFI/refind/themes/refind-theme-regular"
    if [[ -f "$src_theme_path/theme.conf" && -d "$boot_mountpoint/EFI/refind" ]]; then
        echo "Copying theme to $dst_theme_path"
        mkdir -p "$boot_mountpoint/EFI/refind/themes"
        mkdir -p $dst_theme_path
        cp -r "$src_theme_path"/* "$dst_theme_path"
    fi

    cat >"$dst_theme_path/theme_dark.conf" <<-EOF
icons_dir themes/refind-theme-regular/icons/128-48
big_icon_size 128
banner themes/refind-theme-regular/icons/128-48/bg_dark.png
selection_big themes/refind-theme-regular/icons/128-48/selection_dark-big.png
selection_small themes/refind-theme-regular/icons/128-48/selection_dark-small.png
font themes/refind-theme-regular/fonts/source-code-pro-extralight-14.png
EOF

}

function copy_efi_drivers() {
    efi_drivers_dir="/usr/local/share/sk-pre/efi-drivers"
    dst_efi_drivers_dir="$boot_mountpoint/EFI/refind/drivers_x64"
    if [ ! -d "$dst_efi_drivers_dir" ]; then
        sudo mkdir -p "$dst_efi_drivers_dir"
    fi

    for file in "$efi_drivers_dir"/*; do
        if [[ -f "$file" && $(file -b "$file") == *"executable"* ]]; then
            sudo cp -f "$file" "$dst_efi_drivers_dir"
        fi
    done
}

function convert_skorionos_icon() {
    svg_path="/usr/share/plymouth/themes/bgrt-skorion/watermark.svg"
    refind_icon_dir="$boot_mountpoint/EFI/refind/themes/refind-theme-regular/icons"
    png_128_path="$refind_icon_dir/128-48/os_skorion.png"
    png_256_path="$refind_icon_dir/256-96/os_skorion.png"
    png_384_path="$refind_icon_dir/384-144/os_skorion.png"
    png_512_path="$refind_icon_dir/512-192/os_skorion.png"
    
    # Scale factor for icon size
    local scale_factor=0.78
    
    if [[ -x "$(command -v rsvg-convert)" && -x "$(command -v magick)" && -f "$svg_path" ]]; then
        # Convert with transparent background and scale image to specified percentage of canvas size
        local size_128
        local size_256
        local size_384
        local size_512
        size_128=$(printf "%.0f" "$(echo "128 * $scale_factor" | bc)")
        size_256=$(printf "%.0f" "$(echo "256 * $scale_factor" | bc)")
        size_384=$(printf "%.0f" "$(echo "384 * $scale_factor" | bc)")
        size_512=$(printf "%.0f" "$(echo "512 * $scale_factor" | bc)")
        
        # Use rsvg-convert for better SVG transparency handling, then extend canvas with magick
        rsvg-convert --background-color=none -w "$size_128" -h "$size_128" "$svg_path" | magick - -gravity center -background none -extent 128x128 "$png_128_path"
        rsvg-convert --background-color=none -w "$size_256" -h "$size_256" "$svg_path" | magick - -gravity center -background none -extent 256x256 "$png_256_path"
        rsvg-convert --background-color=none -w "$size_384" -h "$size_384" "$svg_path" | magick - -gravity center -background none -extent 384x384 "$png_384_path"
        rsvg-convert --background-color=none -w "$size_512" -h "$size_512" "$svg_path" | magick - -gravity center -background none -extent 512x512 "$png_512_path"
    fi
}


case $ACTION in
install)
    install_refind
    setup_refind
    ;;
uninstall)
    uninstall_refind
    ;;
setup)
    setup_refind
    ;;
*)
    echo "Invalid action. usage: $0 [install|uninstall|setup]"
    exit 1
    ;;
esac
